package com.elcom.roaming.common.db;

import java.sql.SQLException;
import java.util.Map;

import org.slf4j.Logger;

import com.elcom.db.DbConnection;
import com.elcom.db.DbConnectionPool;
import com.elcom.db.SQLUtil;

public class DBQuery {
	private final Logger logger;
	private final DbConnectionPool dbPool;

	public DBQuery(Logger logger, DbConnectionPool dbPool) {
		super();
		this.logger = logger;
		this.dbPool = dbPool;
	}

	public String searchMSISDN(String imsi) throws SQLException, InterruptedException{
		String msisdn = null;
		try {
			DBConnectionImpl dbConn = getConnection();
			try {
				msisdn = dbConn.searchMSISDN(imsi);
			} catch (SQLException ex) {
				if (logger.isErrorEnabled())
					logger.error("Failed to load all active call filter --> ["
							+ SQLUtil.printSQLExceptions(ex) + "]");
				throw ex;
			} finally {
				dbPool.freeConnection(dbConn);
			}
		} catch (SQLException ex) {
			if (logger.isErrorEnabled())
				logger.error("Failed to get db connection --> [" + SQLUtil.printSQLExceptions(ex) + "]");
			throw ex;
		}
		return msisdn;
	}

	public void insertIMSI_MSISDN(Map<String, String> map) throws InterruptedException, SQLException{
		try {
			DBConnectionImpl dbConn = getConnection();
			try {
				dbConn.insertIMSI_MSISDN(map);
			} catch (SQLException ex) {
				if (logger.isErrorEnabled())
					logger.error("Failed to load all active call filter --> ["
							+ SQLUtil.printSQLExceptions(ex) + "]");
				throw ex;
			} finally {
				dbPool.freeConnection(dbConn);
			}
		} catch (SQLException ex) {
			if (logger.isErrorEnabled())
				logger.error("Failed to get db connection --> [" + SQLUtil.printSQLExceptions(ex) + "]");
			throw ex;
		}
	}
	
	private DBConnectionImpl getConnection() throws SQLException,
			InterruptedException {
		DbConnection conn = dbPool.getConnection();
		if (conn == null) {
			throw new SQLException("Connection is not established");
		}
		return (DBConnectionImpl) conn;
	}
}
